import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;

/**
 * This class creates a database of answers to questions that were asked
 * in an RFP(Request For Proposal).
 * @author Ridwan Abdilahi
 * @version 1.0
 */
public class AnswerBank {
	
	/**
	 * A HashMap that pairs keywords to a list of answers that
	 * that have been pre-approved by the system administrator.
	 */
	private HashMap<String, ArrayList<String>> keywords;
	/**
	 * A scanner that is used to read in the text file that
	 * holds the keywords and answers.
	 */
	private Scanner myScanner;
	/**
	 * A public constructor that automatically populates the answer bank from a file.
	 */
	public AnswerBank() {
		keywords = new HashMap<String, ArrayList<String>>();
		myScanner = null;
		populateAnswers();
		
	}
	
	/**
	 * This function populates the keywords HashMap with keywords and answers from
	 * the input file.
	 */
	private void populateAnswers() {
		/*The file to be read is initialized.*/
		InputStream file = getClass().getResourceAsStream("/input.txt");
		
		try {

			/*The scanner is switched to skip over the specified delimmiter*/
			myScanner = new Scanner(file);
			myScanner.useDelimiter(":");
			
			while (myScanner.hasNext()) {
				String key = myScanner.next();
				
				/*If the keyword that is being searched for exists, add the answer
				  to its existing list of answers.*/
				if(keywords.containsKey(key)) {
					String value = myScanner.next();
					keywords.get(key).add(value);
				}
				/*If the keyword that is being searched for does not exist, create a new key
				  for the keyword and add the answer to its list of answers.*/
				else {
					String value = myScanner.next();
					ArrayList<String> list = new ArrayList<String>();
					list.add(value);
					keywords.put(key, list);
				}
				
				/*This statement skips over the new line character if it exists.*/
				if(myScanner.hasNext()) {

					myScanner.next();
				}
			}
			/*If the file does not exist, catch the File Not Found exception and
			  print its stack trace.*/
		} catch (Exception e) {
			e.printStackTrace();
			
		} finally {
			myScanner.close();
		}
	}
	
	/**
	 * This function takes a keyword and searches through the HashMap of keys
	 * to see if this keyword exists.
	 * @param key The keyword to be searched for.
	 * @return If the key exists, the list of answers it is mapped
	 * 		   to will be returned. If it does not exist, a 
	 * 		   blank list will be returned.
	 */
	public List<String> search(String key) {
		if(!keywords.containsKey(key)) {
			return new ArrayList<String>();
		}
		//Commented out by Brian
		/*for (int i = 0; i < keywords.get(key).size(); i++) {
			System.out.println(i + 1 + ".) " + keywords.get(key).get(i));
		}*/
		return keywords.get(key);
	}
	
}
